import 'dart:convert';

import 'package:explore/act/slide.dart';
import 'package:explore/my/person.dart';
import 'package:fluent_ui/fluent_ui.dart' as fluent;
import 'package:flutter/material.dart' hide Page;
import 'package:fluttertoast/fluttertoast.dart';
import '../tool/inputbox.dart';
import 'package:http/http.dart' as http;
import '../provider/person_info.dart';
import 'package:provider/provider.dart';

class Act extends StatefulWidget {
  const Act({super.key});

  @override
  State<StatefulWidget> createState() => _Act();
}

class _Act extends State<Act> {
  var keyword = "";
  var ActName = "";
  double keyCount = 0;
  double keyMaxCount = 0;
  List keylist = [];
  void setKeyword(String value) {
    keylist = value.split(" ");
    setState(() {
      keyMaxCount = keylist.length.toDouble();
      keyword = value;
    });
  }

  void setkeyCount(double value) {
    setState(() {
      keyCount = value;
    });
  }

  void setActName(String value) {
    setState(() {
      ActName = value;
    });
  }

  void uploadAct(PersonInfo person) async {
    final url = Uri.parse('http://127.0.0.1:5000/act');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body =
        jsonEncode({'name': ActName, 'key': keyword, 'count': keyCount});

    final request = http.Request('get', url);
    request.headers.addAll(headers);
    request.body = body;
    final response = await request.send();
    if (response.statusCode == 200) {
      Fluttertoast.showToast(msg: '已确认行动');
      keylist = keyword.split(" ");

      person.changAct(value: ActName);
      person.changKeyword(value: keylist);
      person.changCount(value: keyCount.toInt());

      setState(() {
        ActName = "";
        keyword = "";
        keyCount = 0;
        keyMaxCount = 0;
      });
    } else {
      Fluttertoast.showToast(msg: '确认行动失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('设置行动'),
        ),
        resizeToAvoidBottomInset: false,
        body: Container(
          height: double.infinity,
          width: double.infinity,
          padding: const EdgeInsets.only(left: 20, right: 20, top: 20),
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('image/actBackground.jpg'),
              fit: BoxFit.cover, // 图片如何适应容器
            ),
          ),
          child: Center(
            widthFactor: 1,
            heightFactor: 1,
            child: Column(
              children: [
                Inputbox(
                    name: "行动名", setFunction: setActName, inputvalue: ActName),
                Inputbox(
                    name: "关键词", setFunction: setKeyword, inputvalue: keyword),
                Keyslide(
                    keyCount: keyCount,
                    setkeyCount: setkeyCount,
                    keyMaxCount: keyMaxCount),
                const SizedBox(height: 20),
                const fluent.InfoBar(
                  title: Text('提示'),
                  content: Text(
                    '关键词一栏每输入一个关键词用(空格)分隔\n'
                    '通过滑动确认关键词的有效数量',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  severity: fluent.InfoBarSeverity.info,
                  isLong: true,
                ),
                KeyButton(uploadAct)
              ],
            ),
          ),
        ));
  }
}

class KeyButton extends StatefulWidget {
  final Function(PersonInfo) uploadAct;
  const KeyButton(this.uploadAct, {super.key});

  @override
  fluent.State<fluent.StatefulWidget> createState() => _KeyButton();
}

class _KeyButton extends State<KeyButton> {
  @override
  fluent.Widget build(fluent.BuildContext context) {
    return Consumer<PersonInfo>(builder: (ctx, person, child) {
      return Container(
          margin: const EdgeInsets.only(top: 30),
          width: 400,
          child: fluent.FilledButton(
              child: const Text(
                '确认',
                style: TextStyle(fontSize: 18),
              ),
              onPressed: () => widget.uploadAct(person)));
    });
  }
}
